package com.chendx.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chendx.common.fastdfs.FastDFSClient;
import com.chendx.model.common.dtos.PageResponseResult;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.wemeida.dtos.WmMaterialDto;
import com.chendx.model.wemeida.pojos.WmMaterial;
import com.chendx.model.wemeida.pojos.WmNewsMaterial;
import com.chendx.model.wemeida.pojos.WmUser;
import com.chendx.utils.WmThreadLocalUtils;
import com.chendx.wemedia.mapper.WmMaterialMapper;
import com.chendx.wemedia.mapper.WmNewsMaterialMapper;
import com.chendx.wemedia.service.MaterialService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by chendx on 2022/3/2.
 */
@Service
@Log4j2
public class MaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements MaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;
    @Value("${fdfs.url}")
    private String fileServerUrl;
    @Autowired
    private WmNewsMaterialMapper newsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传图片到fasfdfs
        String fileId = null;
        try {
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        WmUser wmUser = WmThreadLocalUtils.get();
        Integer apUserId = wmUser.getId();
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(apUserId);
        wmMaterial.setType((short) 1);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        save(wmMaterial);
        wmMaterial.setUrl(fileServerUrl + fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        Integer uid = WmThreadLocalUtils.get().getId();
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmMaterial::getUserId, uid);
        if (!StringUtils.isEmpty(dto.getIsCollected())) {
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollected());
        }

        Page page = new Page(dto.getPage(), dto.getSize());
        IPage<WmMaterial> result = page(page, queryWrapper);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());
        List<WmMaterial> datas = result.getRecords();
        List<WmMaterial> wmMaterialList = new ArrayList<>();
        for (WmMaterial wmMaterial : datas) {
            wmMaterial.setUrl(fileServerUrl + wmMaterial.getUrl());
            wmMaterialList.add(wmMaterial);
        }
        pageResponseResult.setData(wmMaterialList);
        return pageResponseResult;
    }

    @Override
    public ResponseResult delPicture(Integer id) {

        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断当前图片是否问引用
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = newsMaterialMapper.selectCount(lambdaQueryWrapper);
        if (count > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前图片被引用");
        }
        String fileId = wmMaterial.getUrl();
        fileId = fileId.replace(fileServerUrl,"");
        //3.删除fastdfs中的图片
        try {
            fastDFSClient.delFile(fileId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        //4.删除数据库中的图片
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新状态
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.get().getId();
        LambdaUpdateWrapper<WmMaterial> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmMaterial::getIsCollection,type);
        updateWrapper.eq(WmMaterial::getId,id);
        updateWrapper.eq(WmMaterial::getUserId,uid);
        update(updateWrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
